import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/',
    component: () => import('../views/Layout.vue'),
    redirect: '/dictionary',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dictionary',
        name: 'Dictionary',
        component: () => import('../views/Dictionary.vue'),
        meta: { title: '领域词典', icon: 'Reading' }
      },
      {
        path: 'documents',
        name: 'Documents',
        component: () => import('../views/DocumentsNew.vue'),
        meta: { title: '文档管理', icon: 'Files' }
      },
      {
        path: 'extract',
        name: 'Extract',
        component: () => import('../views/ExtractNew.vue'),
        meta: { title: '知识抽取', icon: 'Document' }
      },
      {
        path: 'graph',
        name: 'Graph',
        component: () => import('../views/Graph.vue'),
        meta: { title: '知识图谱', icon: 'Connection' }
      },
      {
        path: 'data',
        name: 'Data',
        component: () => import('../views/Data.vue'),
        meta: { title: '数据展示', icon: 'DataLine' }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/Users.vue'),
        meta: { title: '用户管理', icon: 'User', requiresAdmin: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 火电知识图谱` : '火电知识图谱构建平台'
  
  // 需要认证的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      next('/login')
      return
    }
  }
  
  // 需要管理员权限的页面
  if (to.meta.requiresAdmin) {
    if (!user.is_admin) {
      next('/')
      return
    }
  }
  
  // 已登录用户不能访问登录/注册页
  if (token && (to.path === '/login' || to.path === '/register')) {
    next('/')
    return
  }
  
  next()
})

export default router

